#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
开发环境检查脚本
检查Mac或Windows系统上是否安装了指定的开发工具
显示系统实际安装的版本号
"""

import subprocess
import sys
import platform
import re
from typing import Dict, Tuple, Optional

class EnvironmentChecker:
    def __init__(self):
        self.os_type = platform.system().lower()
        # 保留参考版本号，仅用于显示建议
        self.reference_versions = {
            'java': '17',
            'python': '3.9',
            'maven': '3.9.9',
            'node': 'v20.6.0',
            'pnpm': '10.8.0',
            'mysql': '8.0',
            'redis': '7.0'
        }
        
    def run_command(self, command: str) -> Tuple[bool, str]:
        """执行命令并返回结果"""
        try:
            result = subprocess.run(
                command.split(),
                capture_output=True,
                text=True,
                timeout=10
            )
            # 对于java -version，输出在stderr中
            output = result.stdout.strip() if result.stdout.strip() else result.stderr.strip()
            return result.returncode == 0, output
        except (subprocess.TimeoutExpired, FileNotFoundError, Exception):
            return False, ""
    
    def check_java(self) -> Tuple[bool, str, str]:
        """检查Java版本"""
        success, output = self.run_command("java -version")
        if not success:
            return False, "未安装", self.reference_versions['java']
        
        # 解析Java版本 - 支持OpenJDK和Oracle JDK格式
        # 匹配 "17.0.15" 或 "1.8.0_xxx" 等格式
        version_match = re.search(r'version "([^"]+)"', output)
        if version_match:
            full_version = version_match.group(1)
            
            # 提取主版本号
            if full_version.startswith('1.'):
                # Java 8及以下版本格式: "1.8.0_xxx"
                major_version_match = re.search(r'1\.(\d+)', full_version)
                if major_version_match:
                    major_version = major_version_match.group(1)
                    return True, f"Java {major_version} ({full_version})", self.reference_versions['java']
            else:
                # Java 9+版本格式: "17.0.15", "11.0.2", etc.
                major_version_match = re.search(r'^(\d+)', full_version)
                if major_version_match:
                    major_version = major_version_match.group(1)
                    return True, f"Java {major_version} ({full_version})", self.reference_versions['java']
            
            # 如果无法解析主版本号，返回完整版本
            return True, f"Java ({full_version})", self.reference_versions['java']
        
        return False, "版本解析失败", self.reference_versions['java']
    
    def check_python(self) -> Tuple[bool, str, str]:
        """检查Python版本"""
        success, output = self.run_command("python3 --version")
        if not success:
            success, output = self.run_command("python --version")
        
        if not success:
            return False, "未安装", self.reference_versions['python']
        
        # 解析Python版本
        version_match = re.search(r'Python ([\d.]+)', output)
        if version_match:
            version = version_match.group(1)
            return True, version, self.reference_versions['python']
        
        return False, "版本解析失败", self.reference_versions['python']
    
    def check_maven(self) -> Tuple[bool, str, str]:
        """检查Maven版本"""
        success, output = self.run_command("mvn --version")
        if not success:
            return False, "未安装", self.reference_versions['maven']
        
        # 解析Maven版本
        version_match = re.search(r'Apache Maven ([\d.]+)', output)
        if version_match:
            version = version_match.group(1)
            return True, version, self.reference_versions['maven']
        
        return False, "版本解析失败", self.reference_versions['maven']
    
    def check_node(self) -> Tuple[bool, str, str]:
        """检查Node.js版本"""
        success, output = self.run_command("node --version")
        if not success:
            return False, "未安装", self.reference_versions['node']
        
        version = output.strip()
        return True, version, self.reference_versions['node']
    
    def check_pnpm(self) -> Tuple[bool, str, str]:
        """检查PNPM版本"""
        success, output = self.run_command("pnpm --version")
        if not success:
            return False, "未安装", self.reference_versions['pnpm']
        
        version = output.strip()
        return True, version, self.reference_versions['pnpm']
    
    def check_mysql(self) -> Tuple[bool, str, str]:
        """检查MySQL版本"""
        success, output = self.run_command("mysql --version")
        if not success:
            return False, "未安装", self.reference_versions['mysql']
        
        # 解析MySQL版本 - 匹配类似 "mysql  Ver 8.0.35 for macos13.3 on x86_64"
        version_match = re.search(r'Ver (\d+\.\d+)', output)
        if version_match:
            version = version_match.group(1)
            return True, f"MySQL {version}", self.reference_versions['mysql']
        
        return False, "版本解析失败", self.reference_versions['mysql']
    
    def check_redis(self) -> Tuple[bool, str, str]:
        """检查Redis版本"""
        success, output = self.run_command("redis-server --version")
        if not success:
            return False, "未安装", self.reference_versions['redis']
        
        # 解析Redis版本 - 匹配类似 "Redis server v=7.0.15"
        version_match = re.search(r'v=(\d+\.\d+)', output)
        if version_match:
            version = version_match.group(1)
            return True, f"Redis {version}", self.reference_versions['redis']
        
        return False, "版本解析失败", self.reference_versions['redis']
    
    def format_result(self, name: str, is_installed: bool, current: str, reference: str) -> str:
        """格式化检查结果"""
        if not is_installed:
            return f"❌ {name:<10} | 未安装 (建议版本: {reference})"
        else:
            return f"✅ {name:<10} | {current} (已安装)"
    
    def check_all(self) -> Dict[str, Tuple[bool, str, str]]:
        """检查所有环境"""
        print(f"正在检查 {platform.system()} 系统的开发环境...\n")
        print("=" * 60)
        
        checks = {
            'Java': self.check_java(),
            'Python': self.check_python(),
            'Maven': self.check_maven(),
            'Node.js': self.check_node(),
            'PNPM': self.check_pnpm(),
            'MySQL': self.check_mysql(),
            'Redis': self.check_redis()
        }
        
        installed_count = 0
        for name, (is_installed, current, reference) in checks.items():
            print(self.format_result(name, is_installed, current, reference))
            if is_installed:
                installed_count += 1
        
        print("=" * 60)
        
        total_tools = len(checks)
        if installed_count == total_tools:
            print(f"🎉 所有环境都已安装！({installed_count}/{total_tools})")
        else:
            missing_count = total_tools - installed_count
            print(f"📊 环境安装情况: {installed_count}/{total_tools} 已安装，{missing_count} 个未安装")
            print("\n安装建议:")
            for name, (is_installed, current, reference) in checks.items():
                if not is_installed:
                    self.print_install_suggestion(name.lower(), reference)
        
        return checks
    
    def print_install_suggestion(self, tool: str, version: str):
        """打印安装建议"""
        suggestions = {
            'java': f"  • Java (建议 {version}): 访问 https://adoptium.net/ 下载",
            'python': f"  • Python (建议 {version}): 访问 https://www.python.org/downloads/",
            'maven': f"  • Maven (建议 {version}): 访问 https://maven.apache.org/download.cgi",
            'node.js': f"  • Node.js (建议 {version}): 访问 https://nodejs.org/ 或使用 nvm",
            'pnpm': f"  • PNPM (建议 {version}): 运行 'npm install -g pnpm'",
            'mysql': f"  • MySQL (建议 {version}): 运行 'brew install mysql'",
            'redis': f"  • Redis (建议 {version}): 运行 'brew install redis'"
        }
        
        if tool in suggestions:
            print(suggestions[tool])

def main():
    """主函数"""
    try:
        checker = EnvironmentChecker()
        checker.check_all()
    except KeyboardInterrupt:
        print("\n检查已取消")
        sys.exit(1)
    except Exception as e:
        print(f"检查过程中出现错误: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()